package com.task.service;

import com.alipay.api.internal.util.file.IOUtils;
import com.util.HTTPRequestUtil;
import com.util.SpringJobBeanFactory;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.concurrent.CompletableFuture;

/**
 * @author: cxt
 * @time: 2023/4/5
 */
@Service
@Slf4j
public class DownloadService {

    // 修改排序
    @Test
    public void test() {
        download("D:\\素材\\1.text", false, "");
    }

    // 合并流媒体
    @Test
    public void te() {
        File folder = new File("D:\\素材\\test\\");
        File[] files = folder.listFiles();
        if (files != null) {
            for (int i = files.length - 1; i > 0; i--) {
                additional(files[i], files[i - 1]);
            }
        }
    }

    /**
     * 将一个文件追加到另一个中
     */
    public void additional(File inFile, File outFile) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(inFile);
            outputStream = new FileOutputStream(outFile, true);

            // todo 最后一个文件不足1024时会产生空数据，复制到倒数第二个中，显示null
            /*
            byte[] bytes = new byte[1024];
            while (inputStream.read(bytes) > 0) {
                outputStream.write(bytes);
            } */

            // 使用IOUtils读取到多少就返回多少完美解决
            byte[] bytes = IOUtils.toByteArray(inputStream);
            outputStream.write(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 文件修改名称 + 排序
     * <p>
     * #####    自定义方法   #####
     */
    public void sorting(String name, int i) {
        String filePath = "D:\\素材\\test/";
        File file = new File(filePath + name);
        if (file.exists()) {
            String newFilePath = filePath + i + ".ts";
            rename(file, newFilePath, i);
        }
//        else {
//            String testFilePath = "D:\\素材\\test/";
//            File testFile = new File(testFilePath + name);
//            if (testFile.exists()) {
//                String newFilePath = testFilePath + i + ".ts";
//                rename(testFile, newFilePath, i);
//            }
//        }
    }

    /**
     * 请求下载
     *
     * @param filePath 文件地址
     * @param savePath 保存地址
     */
    public void download(String filePath, boolean isRequest, String savePath) {
        FileReader reader = null;
        BufferedReader buf = null;
        try {
            reader = new FileReader(filePath);
            buf = new BufferedReader(reader);
            String line = buf.readLine();
            String url = line;
            int i = 1;
            while (line != null) {
                // 判断是否是url
                if (line.length() > 50) {
                    line = buf.readLine();
                    continue;
                }
                // # 开头不要
                if (line.startsWith("#")) {
                    line = buf.readLine();
                    continue;
                }
                // 请求数据
                if (isRequest) {
                    requestGet(url, line, savePath);
                } else {
                    // 修改名称排序
                    sorting(line, i++);
                }

                // 读取下一行内容
                line = buf.readLine();
            }

            System.out.println("请求结束！\n\n\n\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (buf != null) {
                    buf.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 网络请求下载
     *
     * @param url      地址
     * @param name     名称
     * @param savePath 保存地址
     */
    private void requestGet(String url, String name, String savePath) {
        ThreadPoolTaskExecutor executor = SpringJobBeanFactory.getBean("myAsyncExecutor");
//        ThreadPoolTaskExecutor executor = new TaskPoolConfig().myAsyncExecutor();
        CompletableFuture.runAsync(() -> {
            byte[] bytes = HTTPRequestUtil.SendGet(url + name);
            FileOutputStream stream = null;
            if (bytes != null) {
                try {
                    String[] split = name.split("/");
                    stream = new FileOutputStream(savePath + split[split.length - 1]);
                    stream.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                try {
                    FileWriter fileWriter = new FileWriter("D://err.txt");
                    fileWriter.write(url + name + "\n");
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }, executor);
    }

    /**
     * 重命名
     */
    public void rename(File file, String newFilePath, int i) {
        // 重命名文件
        File newFile = new File(newFilePath);
        if (!file.renameTo(newFile)) {
            // 命名失败
            System.err.println("重命名失败：" + file.getName() + "-" + i);
        }
    }


}
